package com.ldc.common.mvvm;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewbinding.ViewBinding;

import com.ldc.common.exception.CommonException;

public abstract class BaseFragment<VB extends ViewBinding> extends Fragment {
    protected VB viewBinding;

    protected abstract VB initViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState);

    protected VB loadViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initViewBinding(inflater, container, savedInstanceState);
    }

    protected abstract void main(Bundle savedInstanceState);



    protected void handleError(CommonException exception) {
        // 处理异常消息
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        try {
            viewBinding = loadViewBinding(inflater, container, savedInstanceState);
        } catch (CommonException exception) {
            handleError(exception);
        }
        if (viewBinding == null) {
            return null;
        }
        return viewBinding.getRoot();
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            main(savedInstanceState);
        } catch (CommonException exception) {
            handleError(exception);
        }
    }
}
